/*
 * 百度在线网络技术（北京）有限公司拥有本软件版权2022并保留所有权利。
 * Copyright 2022, Baidu.com,Inc 2:Baidu Online Network Technology (Beijing) Co.,Ltd,
 * All rights reserved.
 */

package com.azdebugit.spring.docother.juc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author azdebugit
 * Date 2021/7/3
 * @version 1.0
 */
public class Loc {
    public static void main(String[] args) {
        Data2 data2 = new Data2();
        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data2.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "A").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data2.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "B").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data2.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "C").start();

        new Thread(() -> {
            for (int i = 0; i < 5; i++) {
                try {
                    data2.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "D").start();
    }
}

class Data2 {
    private int num = 0;

    Lock lock = new ReentrantLock();//定义锁
    Condition condition = lock.newCondition();//定义同步监视器

    public int getNum() {
        return num;
    }

    //增加
    public void increment() throws InterruptedException {
        lock.lock();//加锁
        try {
            //判断等待
            while (num != 0) {
                condition.await();//等待
            }
            //业务代码
            num++;
            System.out.println(Thread.currentThread().getName() + " -->  " + num);
            //通知
            condition.signalAll();
        } finally {
            lock.unlock();//解锁
        }
    }

    //减少
    public void decrement() throws InterruptedException {
        lock.lock();//加锁
        try {
            //判断等待
            while (num == 0) {
                condition.await();//等待
            }
            //业务代码
            num--;
            System.out.println(Thread.currentThread().getName() + "  -->  " + num);
            //通知
            condition.signalAll();
        } finally {
            lock.unlock();//解锁
        }
    }
}
